import React, { Component } from 'react';
import { connect } from 'dva';
import { Card, Table, Divider, Spin } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './index.less';

const { Description } = DescriptionList;

@connect(state => ({
  typeInfo: state.assetType.typeInfo,
  loading: state.assetType.loading,
}))
export default class AssetTypeDetail extends Component {
  state = {
    curType: undefined,
  }

  componentDidMount() {
    const { id } = this.props.match.params;
    const { dispatch } = this.props;
    if (!id) {
      return;
    }
    dispatch({
      type: 'assetType/fetchType',
      payload: { id },
    });
  }

  componentWillReceiveProps(nextProps) {
    const { loading, typeInfo } = nextProps;
    if (!loading && typeInfo) {
      const info = typeInfo.reduce((acc, cur) => {
        acc.type_name = cur.type_name;
        acc.status = cur.status;
        if (cur.attr_name && cur.version) {
          acc.attrs.push({
            attr_name: cur.attr_name,
            version: cur.version,
          });
        }
        return acc;
      }, {
        attrs: [],
      });
      this.setState({ curType: info });
    }
  }

  render() {
    const { loading } = this.props;
    const curInfo = this.state.curType;

    if (loading || !this.state.curType) {
      return (<Spin />);
    }

    const attrColumns = [];
    const showTitle = {
      attr_name: '属性名',
      version: '对应版本',
    };

    if (typeof curInfo === 'object' && curInfo.attrs) {
      const head = curInfo.attrs && curInfo.attrs[0];
      for (const attr in head) {
        if (head[attr]) {
          attrColumns.push({
            title: showTitle[attr],
            dataIndex: attr,
            key: attr,
          });
        }
      }
    }

    return (
      <PageHeaderLayout title="类型详情">
        <DescriptionList size="large" title="用户信息" style={{ marginBottom: 32 }}>
          <Description term="资产名">{curInfo.type_name}</Description>
          <Description term="资产状态">{curInfo.status}</Description>
          <Description term="备注" />
        </DescriptionList>
        <Card bordered={false}>
          <Divider style={{ marginBottom: 32 }} />
          <div className={styles.title}>资产信息</div>
          {curInfo.attrs.length > 0 ? (
            <Table
              style={{ marginBottom: 24 }}
              pagination={false}
              loading={loading}
              dataSource={curInfo.attrs}
              columns={attrColumns}
              rowKey={(record, index) => index}
            />
          ) : (
            <div>暂无属性</div>
            )}
        </Card>
      </PageHeaderLayout>
    );
  }
}
